// Ansible Command 语言定义和智能提示
import * as monaco from 'monaco-editor'
import { provideCompletions } from './ansibleCompletion.js'

// 全局变量来跟踪注册状态
let commandLanguageRegistered = false
let commandCompletionProvider = null

// 注册Ansible Command语言
export const registerAnsibleCommandLanguage = () => {
  // 先清理之前的注册
  unregisterAnsibleCommandLanguage()

  // 避免重复注册
  if (commandLanguageRegistered) {
    console.log('Ansible Command语言已注册，跳过重复注册')
    return
  }

  try {
    // 注册语言
    monaco.languages.register({ id: 'ansible-command' })
    console.log('注册Ansible Command语言成功')

    // 设置语言配置
    monaco.languages.setLanguageConfiguration('ansible-command', {
      wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
      comments: {
        lineComment: '#'
      },
      brackets: [
        ['{', '}'],
        ['[', ']'],
        ['(', ')'],
        ['"', '"'],
        ["'", "'"]
      ],
      autoClosingPairs: [
        { open: '{', close: '}' },
        { open: '[', close: ']' },
        { open: '(', close: ')' },
        { open: '"', close: '"', notIn: ['string'] },
        { open: "'", close: "'", notIn: ['string', 'comment'] }
      ]
    })

    // 设置语法高亮
    monaco.languages.setMonarchTokensProvider('ansible-command', {
      tokenizer: {
        root: [
          // 注释
          [/#.*$/, 'comment'],

          // ansible命令关键字
          [/\bansible\b/, 'keyword.control'],
          [/\bansible-playbook\b/, 'keyword.control'],
          [/\bansible-vault\b/, 'keyword.control'],
          [/\bansible-galaxy\b/, 'keyword.control'],

          // 选项参数
          [/-[a-zA-Z]/, 'variable.parameter'],
          [/--[a-zA-Z-]+/, 'variable.parameter'],

          // 模块名（-m 后面的内容）
          [/(?<=-m\s+)[a-zA-Z_][a-zA-Z0-9_]*/, 'entity.name.function'],

          // 字符串
          [/"([^"\\]|\\.)*$/, 'string.invalid'],
          [/'([^'\\]|\\.)*$/, 'string.invalid'],
          [/"/, 'string', '@string_double'],
          [/'/, 'string', '@string_single'],

          // 数字
          [/\d+/, 'number'],

          // IP地址
          [/\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/, 'number.ip'],

          // 主机名和组名
          [/[a-zA-Z][a-zA-Z0-9\-_.]*/, 'variable.name'],

          // 操作符
          [/[=:]/, 'operator'],

          // 空白字符
          [/[ \t\r\n]+/, 'white']
        ],

        string_double: [
          [/[^\\"]+/, 'string'],
          [/\\./, 'string.escape'],
          [/"/, 'string', '@pop']
        ],

        string_single: [
          [/[^\\']+/, 'string'],
          [/\\./, 'string.escape'],
          [/'/, 'string', '@pop']
        ]
      }
    })

    // 设置自定义主题
    monaco.editor.defineTheme('ansible-command-dark', {
      base: 'vs-dark',
      inherit: false,
      rules: [
        // 注释 - 绿色斜体
        { token: 'comment', foreground: '6A9955', fontStyle: 'italic' },

        // ansible命令关键字 - 亮蓝色粗体
        { token: 'keyword.control', foreground: '569CD6', fontStyle: 'bold' },

        // 参数选项 - 紫色
        { token: 'variable.parameter', foreground: 'C586C0' },

        // 模块名 - 黄色
        { token: 'entity.name.function', foreground: 'DCDCAA' },

        // 字符串 - 橙色
        { token: 'string', foreground: 'CE9178' },
        { token: 'string.escape', foreground: 'D7BA7D' },
        { token: 'string.invalid', foreground: 'F44747' },

        // 数字 - 浅绿色
        { token: 'number', foreground: 'B5CEA8' },
        { token: 'number.ip', foreground: '4FC1FF' },

        // 变量名 - 浅蓝色
        { token: 'variable.name', foreground: '9CDCFE' },

        // 操作符 - 白色
        { token: 'operator', foreground: 'D4D4D4' },

        // 默认文本
        { token: '', foreground: 'D4D4D4' }
      ],
      colors: {
        'editor.background': '#1E1E1E',
        'editor.foreground': '#D4D4D4',
        'editor.lineHighlightBackground': '#2D2D30',
        'editor.selectionBackground': '#264F78',
        'editorCursor.foreground': '#AEAFAD',
        'editorWhitespace.foreground': '#404040'
      }
    })

    // 注册智能提示提供者
    commandCompletionProvider = monaco.languages.registerCompletionItemProvider('ansible-command', {
      provideCompletionItems: async (model, position, context, token) => {
        try {
          const lineContent = model.getLineContent(position.lineNumber)
          const textBeforeCursor = lineContent.substring(0, position.column - 1)

          console.log('智能提示被触发，位置:', position, '内容:', lineContent, '光标前文本:', textBeforeCursor)

          // 如果没有输入任何内容，不显示提示
          if (!textBeforeCursor.trim()) {
            console.log('没有输入内容，不显示智能提示')
            return { suggestions: [] }
          }

          // 获取当前选择的inventory ID（如果有的话）
          const inventoryId = window.currentInventoryId || null
          const result = await provideCompletions(model, position, inventoryId)
          console.log('智能提示结果:', result)
          return result
        } catch (error) {
          console.error('Ansible命令智能提示失败:', error)
          return { suggestions: [] }
        }
      },
      triggerCharacters: [' ', '-', 'm']
    })

    // 标记为已注册
    commandLanguageRegistered = true
    console.log('Ansible Command语言和智能提示注册成功')
  } catch (error) {
    console.error('注册Ansible Command语言失败:', error)
  }
}

// 清理Ansible Command语言注册
export const unregisterAnsibleCommandLanguage = () => {
  if (commandCompletionProvider) {
    try {
      commandCompletionProvider.dispose()
      commandCompletionProvider = null
      console.log('Ansible Command智能提示提供者已清理')
    } catch (error) {
      console.error('清理Ansible Command智能提示提供者失败:', error)
    }
  }

  // 重置注册状态
  commandLanguageRegistered = false
}

// 设置当前inventory ID（供智能提示使用）
export const setCurrentInventoryId = (inventoryId) => {
  window.currentInventoryId = inventoryId
}

// 获取默认的Ansible命令内容
export const getDefaultAnsibleCommand = () => {
  return `ansible all -m ping`
}
